package com.lakala.sh.zf.openplatform.common;

import org.apache.commons.codec.binary.Hex;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;

/**
 * @Author peijian
 * @Date 2021/1/18 17:08
 * @Version 1.0
 */
public class SecureUtils {

    /**
     * @description 私钥签名
     * @param signAlgorithm ---- SHA1withRSA & SHA256withRSA
     * @param data
     * @param privateKey
     * @return
     */
    public static byte[] sign(String signAlgorithm, byte[] data, PrivateKey privateKey) {
        try {
            System.out.println("得到签名算法：" +signAlgorithm);
            // 构建签名，由证书指定签名算法
            Signature signature = Signature.getInstance(signAlgorithm);
            // 初始化签名，由私钥构建
            signature.initSign(privateKey);
            signature.update(data);
            return signature.sign();
        } catch (Exception e) {
            System.out.println("私钥签名异常,"+e);
        }
        return  null;
    }

    /**
     * @description 公钥验签
     * @param signAlgorithm ---- SHA1withRSA & SHA256withRSA
     * @param data
     * @param publicKey
     * @param signdata
     * @return
     */
    public static boolean verify(String signAlgorithm, byte[] data, PublicKey publicKey, byte[] signdata) {
        long stratTime = System.currentTimeMillis();
        try {
            // 由证书构建签名
            Signature signature = Signature.getInstance(signAlgorithm);
            // 由证书初始化签名，实际上是使用了证书中的公钥
            signature.initVerify(publicKey);
            signature.update(data);
            boolean isSignOK = signature.verify(signdata);
            System.out.println("验签结果：" +isSignOK);
            if (!isSignOK) {
                return false;
            }
        } catch (Exception e) {//交易未知异常
            System.out.println("交易数据验证签名出现异常 data="+e);
            return false;
        } finally {//组返回包，并异步修改流水表
        }
        return true;
    }

}
